package cn.howxu.yichen_ovo.common.item.api;

import cn.howxu.yichen_ovo.common.entity.EntityPainting;
import cn.howxu.yichen_ovo.registry.api.PaintingType;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;

import java.util.function.Supplier;

/**
 * @description: TODO
 * @author: HowXu
 * @date: 2025/10/4 14:54
 */
public abstract class PaintItem extends Item {

    // PaintingVariant variant
    private final Supplier<PaintingType> paintingSupplier;

    public PaintItem(Properties properties, Supplier<PaintingType> paintingDimension) {
        super(properties);
        this.paintingSupplier = paintingDimension;
    }

    public InteractionResult useOn(UseOnContext useContext) {
        BlockPos pos = useContext.getClickedPos();
        Direction direction = useContext.getClickedFace();
        BlockPos relativePos = pos.relative(direction);
        Player player = useContext.getPlayer();
        ItemStack stack = useContext.getItemInHand();
        if (player != null && !this.mayPlace(player, direction, stack, relativePos)) {
            return InteractionResult.FAIL;
        } else {
            Level level = useContext.getLevel();
            EntityPainting entityPainting = new EntityPainting(level, relativePos, direction, paintingSupplier.get());
            entityPainting.setItem(stack);

            CompoundTag tag = stack.getTag();
            if (tag != null) {
                EntityType.updateCustomEntityTag(level, player, entityPainting, tag);
            }

            if (entityPainting.survives()) {
                if (!level.isClientSide) {
                    entityPainting.playPlacementSound();
                    level.addFreshEntity(entityPainting);

                    stack.shrink(1);
                }

                return InteractionResult.sidedSuccess(level.isClientSide);
            } else {
                return InteractionResult.CONSUME;
            }
        }
    }

    protected boolean mayPlace(Player player, Direction direction, ItemStack stack, BlockPos pos) {
        return !direction.getAxis().isVertical() && player.mayUseItemAt(pos, direction, stack);
    }
}
